<script setup>
import {onMounted, reactive, ref, watch} from "vue";
import {useRoute} from "vue-router";
import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";
import AddNewsArticle from "../ming/addNewsArticle.vue"
const tableData=ref([])
const formInline=ref({})
const typeId=ref(-1);
const currentPage = ref(1)
const pageSize =ref(4);
const total =ref(0)
const handleSizeChange =(val)=>{
  pageSize.value=val;
  initData(typeId.value);
}
const handleCurrentChange =(val)=>{
  currentPage.value=val;
  initData(typeId.value);
}
const initData=(id)=>{
  axios.post(`/news/getNewsByType/${id}/${currentPage.value}/${pageSize.value}`,formInline.value).then(resp=>{
    tableData.value=resp.data.data;
    total.value=resp.data.total;
  })
}
const props=defineProps({
  typeId:{
    type:[String,Number],
    required:true
  }
})
watch(()=>props.typeId,(newValue)=>{
  initData(newValue);
})
onMounted(()=>{
  typeId.value=props.typeId;
  initData(typeId.value);
  getAuthors();
})
const news=ref({})
const handleEdit =(row)=>{
  visible.value=true;
  axios.get(`/news/getNewsById/${row.id}`).then(resp=>{
    news.value=resp.data;
  })
}
const handleDelete =(row)=>{
  ElMessageBox.confirm(
      '<strong>确定要删除这些数据吗？</strong><br><span style="color: red;">删除后无法恢复</span><br><span style="color: gray;">请问还要继续吗？</span>',
      'Warning',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }
  )
      .then(() => {
        axios.delete(`/news/deleteNewsById/${row.id}`).then(resp=>{
          ElMessage.success(resp.data)
          initData(typeId.value);
        }).catch(err=>{
          ElMessage.error(err.response.data)
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: 'Delete canceled',
        })
      })
}
const handleOffShelve =(row)=>{
  axios.put(`/news/offShelve/${row.id}`).then(resp=>{
    ElMessage.success(resp.data)
    initData(typeId.value);
  })
}
const resetForm=()=>{
  formInline.value={}
}
const query = ()=>{
  initData(typeId.value);
}
const editorOptions=ref([])
const getAuthors=()=>{
  axios.get("/news/getAuthors").then(resp=>{
    editorOptions.value=resp.data.map((item, index) => ({
      label: item.author,
      value: item.author
    }));
  })
}
const statusOptions=ref([
  {value:0,label:'未通过'},
  {value:1,label:'草稿'},
  {value:2,label:'审核中'},
  {value:3,label:'已通过'},
  {value:4,label:'已发布'},
  {value:5,label:'已下架'}
])

const visible=ref(false);
const addNewsArticle = ()=>{
  visible.value=true;
}
const getDialogVisible =(val)=>{
  visible.value=val;
}
const handleSticky =(row)=>{
  axios.put(`/news/sticky/${row.id}`).then(resp=>{
    ElMessage.success(resp.data)
    initData(typeId.value);

  })
}
const cancelSticky =(row)=>{
  axios.put(`/news/cancelSticky/${row.id}`).then(resp=>{
    ElMessage.success(resp.data)
    initData(typeId.value);
  })
}
const submit =(row)=>{
  axios.put(`/news/submit/${row.id}`).then(resp=>{
    ElMessage.success(resp.data)
    initData(typeId.value);
  })
}
const withdraw =(row)=>{
  axios.put(`/news/withdraw/${row.id}`).then(resp=>{
    ElMessage.success(resp.data)
    initData(typeId.value);
  })
}
const statusMap = reactive({
  0: { text: '未通过', type: 'danger' },
  1: { text: '草稿', type: 'info' },
  2: { text: '审核中', type: 'primary' },
  3: { text: '已通过', type: 'info' },
  4: { text: '已发布', type: 'info' },
  5: { text: '已下架', type: 'info' }
});
const getStatusInfo = (status)=>{
  return statusMap[status];
}
const getButtons =(row)=>{
  if (row.status ===4 && row.topLevel === 0) {
    return ["handleSticky","handleEdit","handleOffShelve","handleDelete"];
  }else if (row.status ===4 && row.topLevel === 1){
    return ["cancelSticky","handleEdit","handleOffShelve","handleDelete"];
  }else if (row.status === 2){
    return ["withdraw","handleDelete"]
  }else if ([0,1,5].includes(row.status)){
    return ["submit","handleEdit","handleDelete"];
  }
  return [];
}
const handleAction =(action,row)=>{
  if (action==="handleSticky") handleSticky(row)
  else if (action=== "cancelSticky") cancelSticky(row)
  else if (action=== "handleEdit") handleEdit(row)
  else if (action=== "handleOffShelve") handleOffShelve(row)
  else if (action=== "handleDelete") handleDelete(row)
  else if (action=== "withdraw") withdraw(row)
  else if (action=== "submit") submit(row)
}
const getButtonText =(action)=>{
  if (action==='handleSticky') return '置顶'
  else if (action==='cancelSticky') return '取消置顶'
  else if (action==='handleEdit') return '编辑'
  else if (action==='handleOffShelve') return '下架'
  else if (action==='handleDelete') return '删除'
  else if (action==='withdraw') return '撤回'
  else if (action==='submit') return '提交'
}
</script>

<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>查询条件</span>
      </div>
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="文章标题：">
          <el-input v-model="formInline.title" placeholder="请输入文章标题"></el-input>
        </el-form-item>
        <el-form-item label="编辑：" style="width: 200px">
          <el-select v-model="formInline.author" placeholder="全部" style="width: 100%">
            <el-option
                v-for="option in editorOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value">
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 使用 v-for 循环生成“状态”下拉框 -->
        <el-form-item label="状态：" style="width: 200px">
          <el-select v-model="formInline.status" placeholder="全部" style="width: 100%">
            <el-option
                v-for="option in statusOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="query">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>资讯列表</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="addNewsArticle">添加资讯</el-button>
      </div>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column label="文章图片" width="120">
          <template #default="scope">
            <el-image
                :src="scope.row.thumbnail"
                fit="cover"
                style="width: 80px; height: 80px"
            />
          </template>
        </el-table-column>

        <el-table-column prop="title" label="文章标题" width="180"></el-table-column>
        <el-table-column prop="readCount" label="阅读量" width="180"></el-table-column>
        <el-table-column prop="commentCount" label="评论数"></el-table-column>
        <el-table-column prop="shareCount" label="分享数"></el-table-column>
        <el-table-column prop="topLevel" label="置顶">
          <template #default="scope">
            <el-tag :type="scope.row.topLevel===0?'info':'danger'">{{scope.row.topLevel===0?'未置顶':'置顶'}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="getStatusInfo(scope.row.status).type">{{getStatusInfo(scope.row.status).text}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="author" label="作者"></el-table-column>
        <el-table-column prop="createTime" label="日期"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
                v-for="action in getButtons(scope.row)"
                :key="action"
                class="mx-1"
                type="text"
                @click="handleAction(action,scope.row)"
            >
              {{getButtonText(action)}}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页组件 -->
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[4, 10, 20, 40]"
        :size="'small'"
        :disabled="false"
        :background="false"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="text-align: center; margin-top: 20px;"
    ></el-pagination>
  </div>
<AddNewsArticle :visible="visible" @dialogVisible="getDialogVisible" :news="news"/>
</template>

<style scoped>
.box-card {
  margin-bottom: 20px;
}
</style>